@model MenuPartEditViewModel
@inject IContentManager ContentManager
@inject OrchardCore.ContentManagement.Display.IContentItemDisplayManager ContentItemDisplayManager
@inject OrchardCore.DisplayManagement.ModelBinding.IUpdateModelAccessor ModelUpdaterAccessor
@inject OrchardCore.ContentManagement.Metadata.IContentDefinitionManager ContentDefinitionManager
@*
    This template is used to render the editor for a Menu content item.
    It render the hierarchy of the menu items.
    The shape is created from MenuPartDisplayDriver
*@

<script asp-src="~/OrchardCore.Menu/Scripts/menu.js" at="Foot" depends-on="admin"></script>
<style asp-src="~/OrchardCore.Menu/Styles/menu.min.css" debug-src="~/OrchardCore.Menu/Styles/menu.css"></style>

@using OrchardCore.ContentManagement.Metadata.Settings;

@{
    var updater = ModelUpdaterAccessor.ModelUpdater;
    var menuItemContentTypes = ContentDefinitionManager.ListTypeDefinitions().Where(t => t.GetSettings<ContentTypeSettings>().Stereotype == "MenuItem");
    var canAddMenuItem = Model.MenuPart.ContentItem.Id != 0;
    var index = 0;
}

<nav class="admin-toolbar">
    <button type="button" @(canAddMenuItem ? null : "disabled=\"disabled\"") class="btn btn-primary" data-toggle="modal" data-target="#modalMenuItems">
        @T["Add Menu Item"]
    </button>
</nav>

<p>
    <ol id="menu">
        @foreach (var menuItem in Model.MenuPart.ContentItem.As<MenuItemsListPart>().MenuItems)
        {
            dynamic menuItemShape = await ContentItemDisplayManager.BuildDisplayAsync(menuItem, updater, "Admin");
            menuItemShape.MenuPart = Model.MenuPart;
            menuItemShape.Index = index++;
            @await DisplayAsync(menuItemShape);
        }
    </ol>
</p>

<!-- Modal -->
<div class="modal fade" id="modalMenuItems" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@T["Available Menu Items"]</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    @foreach (var type in menuItemContentTypes)
                    {
                        var menuItem = await ContentManager.NewAsync(type.Name);
                        dynamic thumbnail = await ContentItemDisplayManager.BuildDisplayAsync(menuItem, updater, "Thumbnail");
                        thumbnail.MenuItemType = type.Name;
                        thumbnail.MenuItemTypeDisplayName = type.DisplayName;
                        thumbnail.MenuContentItemId = Model.MenuPart.ContentItem.ContentItemId;
                        <div class="col-sm-6">
                            @await DisplayAsync(thumbnail)
                        </div>
                    }
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">@T["Cancel"]</button>
            </div>
        </div>
    </div>
</div>

<input asp-for="Hierarchy" type="hidden" value="" />
<div id="msg-leave" style="display:none" data>@T["You have reordered the navigation."]</div>

<script at="Foot">
    var menuItemId;
    var confirmLeave;

    $('#modalMenuItems').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget) // Button that triggered the modal
        menuItemId = button.data('menuitemid') // Extract info from data-* attributes
    })

    $('.thumbnail-link-create').on('click', function () {
        // there is no value for a new root menu item
        if (menuItemId) {
            var link = $(this);
            var href = link.attr('href');
            href += '&menuitemid=' + menuItemId;
            link.attr('href', href);
        }
    });

    $(function () {
        $('#menu')
            .nestedSortable({
                handle: 'div.menu-item-title',
                items: 'li.menu-item',
                toleranceElement: '> div.menu-item-title',
                relocate: function () {
                    confirmLeave = true;
                    $('#@Html.IdFor(m => m.Hierarchy)').attr('value', JSON.stringify($('#menu').nestedSortable('toHierarchy')));
                }
            });

        window.onbeforeunload = function () {
            if (confirmLeave) {
                return $('#msg-leave').text();
            }
        }

        $('#menu').closest("form").on('submit', function (e) {
            confirmLeave = false;
            window.onbeforeunload = function () { };
        });
    });
</script>
